import axios from 'axios'
import { loading, toast } from '@/utils/feedback'
import { qnToken } from '@/api/qn-token'

function toBlob(base64Text) {
  const buffer = atob(base64Text.split(',')[1])
    .split('')
    .map((char) => char.charCodeAt(0))
  const blob = new Blob([new Uint8Array(buffer)], { type: 'image/png' })
  return blob
}

export async function upload(file) {
  loading.show()
  const token = await qnToken()
  const fd = new FormData()
  fd.append('token', token)
  fd.append('file', file)
  try {
    const { data = {} } = await axios({
      url: 'https://upload.qiniup.com',
      method: 'post',
      data: fd,
    })
    loading.hide()
    return { ...data, url: `${data.base_url}${data.path}` }
  } catch (e) {
    toast(e.message || '上传错误')
    loading.hide()
    return Promise.reject(e)
  }
}

export function uploadBase64(base64Text) {
  const file = toBlob(base64Text)
  return upload(file)
}

